package zheezes.eisp.collect.model;

import java.util.Calendar;

import org.apache.log4j.Logger;

import zheezes.eisp.data.orm.CalcTask;
import zheezes.eisp.data.orm.Summator;
import zheezes.eisp.data.orm.SummatorDailyFrozenData;
import zheezes.util.DateFormatUtil;


public abstract class SummatorDailyFrozenCollectTaskHandler extends CollectTaskHandler {
	private static final Logger logger = Logger.getLogger(SummatorDailyFrozenCollectTaskHandler.class);
	
	/**
	 * check if need to add daily calc
	 */
	protected void checkSummatorDailyUse(Summator sm, Calendar cal) {
		logger.debug(String.format("check summator[%s] %s daily use", sm.getId(), DateFormatUtil.getDateFmt().format(cal.getTime())));
		CalcTask task = new CalcTask();
		task.setTaskType(CalcTask.TASK_CALC_USE);
		task.setTargetType(CalcTask.TARGET_SUMMETER);
		task.setTargetId(sm.getId());
		task.setStatus(CalcTask.STATUS_QUEUE);
		task.setSource(CalcTask.SOURCE_AUTO);
		
		Calendar tc = Calendar.getInstance();
		SummatorDailyFrozenData smdf = null;
		
		tc.setTime(cal.getTime());
		tc.add(Calendar.DATE, -1);
		smdf = dataAccessor.querySummatorDailyFrozenDataByMpIdAndDate(sm.getMpId(), tc.getTime());
		if(smdf != null) {
			task.setDate(tc.getTime());
			task.setCreateDate(Calendar.getInstance().getTime());
			dataAccessor.replaceCalcTask(task);
		}
		
		tc.setTime(cal.getTime());
		tc.add(Calendar.DATE, 1);
		smdf = dataAccessor.querySummatorDailyFrozenDataByMpIdAndDate(sm.getMpId(), tc.getTime());
		if (smdf != null) {
			task.setDate(cal.getTime()); // different with yesterday data
			task.setCreateDate(Calendar.getInstance().getTime());
			dataAccessor.replaceCalcTask(task);
		}
	}
}
